package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")   //声明切入点
    public void validRange(){}

    /**
     * 在切入点执行之前调用
     */
    @Before("validRange()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段的填充......");

        //拿到第一个参数，规定为与数据库对应的实体
        Object[] objects = joinPoint.getArgs();
        if (objects==null||objects.length==0){
            return;
        }
        Object entity=objects[0];

        //拿到方法上的注解
        AutoFill autoFill = ((MethodSignature) joinPoint.getSignature()).getMethod()
                                                        .getAnnotation(AutoFill.class);

        //判断注解的类型
        if (autoFill.value()== OperationType.UPDATE){
            try {
                entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(entity,LocalDateTime.now());
                entity.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(entity,BaseContext.getCurrentId());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(autoFill.value()==OperationType.INSERT){
            try {
                entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(entity,LocalDateTime.now());
                entity.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(entity,BaseContext.getCurrentId());
                entity.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class).invoke(entity,LocalDateTime.now());
                entity.getClass().getDeclaredMethod("setCreateUser", Long.class).invoke(entity,BaseContext.getCurrentId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
